<template>
  <div class="data-table-section">
    <div class="section-header">
      <h3>历史数据记录</h3>
      <div class="table-controls">
        <el-button size="small" @click="handleRefresh">
          <i class="el-icon-refresh"></i>
          刷新
        </el-button>
        <el-button size="small" @click="handleExportTable">
          <i class="el-icon-download"></i>
          导出表格
        </el-button>
        <el-dropdown @command="handleTableAction">
          <el-button size="small">
            更多操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="columns">自定义列</el-dropdown-item>
            <el-dropdown-item command="density">表格密度</el-dropdown-item>
            <el-dropdown-item command="fullscreen">全屏显示</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="dataList"
        :height="tableHeight"
        stripe
        border
        :size="tableSize"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange">

        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />

        <el-table-column
          label="设备信息"
          min-width="150"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="device-info">
              <div class="device-name">{{ scope.row.deviceName || scope.row.deviceCode }}</div>
              <div class="device-code">{{ scope.row.deviceCode }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="能耗类型"
          prop="energyType"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-tag :type="getEnergyTypeTag(scope.row.energyType)" size="small">
              {{ getEnergyTypeName(scope.row.energyType) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="电压(V)"
          prop="voltage"
          width="100"
          align="center"
          sortable="custom">
          <template slot-scope="scope">
            <span :class="getValueClass('voltage', scope.row.voltage)">
              {{ formatValue(scope.row.voltage, 2) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          label="电流(A)"
          prop="current"
          width="100"
          align="center"
          sortable="custom">
          <template slot-scope="scope">
            <span :class="getValueClass('current', scope.row.current)">
              {{ formatValue(scope.row.current, 2) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          label="功率(kW)"
          prop="power"
          width="100"
          align="center"
          sortable="custom">
          <template slot-scope="scope">
            <span :class="getValueClass('power', scope.row.power)">
              {{ formatValue(scope.row.power, 2) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          label="累计能耗(kWh)"
          prop="totalEnergy"
          width="120"
          align="center"
          sortable="custom">
          <template slot-scope="scope">
            {{ formatValue(scope.row.totalEnergy, 2) }}
          </template>
        </el-table-column>

        <el-table-column
          label="功率因数"
          prop="powerFactor"
          width="100"
          align="center">
          <template slot-scope="scope">
            {{ formatValue(scope.row.powerFactor, 3) }}
          </template>
        </el-table-column>

        <el-table-column
          label="温度(℃)"
          prop="temperature"
          width="100"
          align="center"
          sortable="custom">
          <template slot-scope="scope">
            <span :class="getValueClass('temperature', scope.row.temperature)">
              {{ formatValue(scope.row.temperature, 1) }}
            </span>
          </template>
        </el-table-column>

        <el-table-column
          label="设备状态"
          prop="status"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusTag(scope.row.status)" size="small">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="数据质量"
          prop="quality"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.quality === '0' ? 'success' : 'warning'" size="small">
              {{ scope.row.quality === '0' ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="采集时间"
          prop="ts"
          width="160"
          align="center"
          sortable="custom">
          <template slot-scope="scope">
            <div class="time-info">
              <div>{{ parseTime(scope.row.ts, '{y}-{m}-{d}') }}</div>
              <div class="time-detail">{{ parseTime(scope.row.ts, '{h}:{i}:{s}') }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="viewDetails(scope.row)">
              详情
            </el-button>
            <el-button type="text" size="small" @click="viewTrend(scope.row)">
              趋势
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <div class="table-info">
          <span>共 {{ total }} 条记录</span>
          <span v-if="selectedRows.length > 0">，已选择 {{ selectedRows.length }} 条</span>
        </div>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="currentPage"
          :limit.sync="pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { parseTime } from '@/utils/ruoyi';

export default {
  name: "DataTable",
  props: {
    dataList: {
      type: Array,
      default: () => []
    },
    total: {
      type: Number,
      default: 0
    },
    loading: {
      type: Boolean,
      default: false
    },
    selectedRows: {
      type: Array,
      default: () => []
    },
    tableHeight: {
      type: Number,
      default: 400
    },
    tableSize: {
      type: String,
      default: 'medium'
    },
    queryParams: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      currentPage: 1,
      pageSize: 20
    };
  },
  methods: {
    parseTime,
    handleRefresh() {
      this.$emit('refresh');
    },
    handleExportTable() {
      this.$emit('export-table');
    },
    handleTableAction(command) {
      this.$emit('table-action', command);
    },
    handleSelectionChange(selection) {
      this.$emit('selection-change', selection);
    },
    handleSortChange(sortInfo) {
      this.$emit('sort-change', sortInfo);
    },
    handlePagination(pagination) {
      this.currentPage = pagination.page;
      this.pageSize = pagination.limit;
      this.$emit('pagination', pagination);
    },
    viewDetails(row) {
      this.$emit('view-details', row);
    },
    viewTrend(row) {
      this.$emit('view-trend', row);
    },
    // 工具方法
    getEnergyTypeName(type) {
      // 支持数字编码和英文名称
      const typeMap = {
        // 数字编码
        '1': '电力',
        '2': '燃气',
        '3': '水',
        '4': '蒸汽',
        '5': '其他',
        // 英文名称
        'electric': '电力',
        'electricity': '电力',
        'power': '电力',
        'gas': '燃气',
        'natural_gas': '燃气',
        'water': '水',
        'steam': '蒸汽',
        'other': '其他',
        'others': '其他'
      };
      return typeMap[String(type)] || type || '-';
    },
    getEnergyTypeTag(type) {
      const tagMap = {
        // 数字编码
        '1': 'primary',   // 电力
        '2': 'warning',   // 燃气
        '3': 'info',      // 水
        '4': 'success',   // 蒸汽
        '5': 'default',   // 其他
        // 英文名称
        'electric': 'primary',
        'electricity': 'primary',
        'power': 'primary',
        'gas': 'warning',
        'natural_gas': 'warning',
        'water': 'info',
        'steam': 'success',
        'other': 'default',
        'others': 'default'
      };
      return tagMap[String(type)] || 'default';
    },
    getStatusName(status) {
      const statusMap = {
        '0': '正常',
        '1': '告警',
        '2': '故障',
        '3': '离线'
      };
      return statusMap[status] || '未知';
    },
    getStatusTag(status) {
      const tagMap = {
        '0': 'success',
        '1': 'warning',
        '2': 'danger',
        '3': 'info'
      };
      return tagMap[status] || 'default';
    },
    formatValue(value, precision = 2) {
      if (value === null || value === undefined || value === '') {
        return '-';
      }
      const num = parseFloat(value);
      return isNaN(num) ? '-' : num.toFixed(precision);
    },
    getValueClass(type, value) {
      const num = parseFloat(value);
      if (isNaN(num)) return '';

      const status = this.getMetricStatus(type, num);
      return {
        'value-normal': status === 'normal',
        'value-warning': status === 'warning',
        'value-danger': status === 'danger'
      };
    },
    getMetricStatus(key, value) {
      const thresholds = {
        power: { warning: 80, danger: 95 },
        voltage: { min: 200, max: 240 },
        current: { warning: 400, danger: 480 },
        temperature: { warning: 60, danger: 75 }
      };

      const threshold = thresholds[key];
      if (!threshold) return 'normal';

      if (key === 'voltage') {
        if (value < threshold.min || value > threshold.max) return 'danger';
        if (value < threshold.min + 10 || value > threshold.max - 10) return 'warning';
      } else {
        if (value >= threshold.danger) return 'danger';
        if (value >= threshold.warning) return 'warning';
      }

      return 'normal';
    }
  }
};
</script>

<style lang="scss" scoped>
.data-table-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }

    .table-controls {
      display: flex;
      gap: 8px;
    }
  }

  .table-card {
    ::v-deep .el-card__body {
      padding: 0;
    }

    .el-table {
      .device-info {
        .device-name {
          font-weight: 500;
          color: #303133;
          margin-bottom: 2px;
        }

        .device-code {
          font-size: 12px;
          color: #909399;
        }
      }

      .time-info {
        .time-detail {
          font-size: 12px;
          color: #909399;
          margin-top: 2px;
        }
      }

      .value-normal {
        color: #67C23A;
      }

      .value-warning {
        color: #E6A23C;
      }

      .value-danger {
        color: #F56C6C;
      }
    }

    .table-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-top: 1px solid #EBEEF5;

      .table-info {
        font-size: 14px;
        color: #606266;

        span {
          margin-right: 16px;
        }
      }
    }
  }
}
</style>
